﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ThoughtWorks.QRCode.Codec;
using MKAdmin.ToolKit.FileKit;

namespace MKAdmin.ToolKit
{
    /// <summary>
    /// 二维码操作
    /// </summary>
    public class QrcodeHelper
    {
        /// <summary>
        /// 返回生成的二维码路径 http://localhost:7799/Qrcode/imgs/20180206/faiejgoal.png
        /// </summary>
        /// <param name="nr"></param>
        /// <returns></returns>
        public static string CreateCode_Simple(string text,bool isAbsolute=false)
        {
            CatalogElement catalogConfig = FileCatalogHelper.Catalog["Qrcode"];
            string catalog = DateTime.Now.ToString("yyyyMMdd");

            string newFileName = Guid.NewGuid().ToString("N") + ".png";
            string newFilePath = string.Format("{0}\\{1}\\{2}", catalogConfig.DestFile.AbsolutePath, catalog, newFileName);

            string dirFile = string.Format("{0}\\{1}", catalogConfig.DestFile.AbsolutePath, catalog);
            if (!System.IO.Directory.Exists(dirFile))
            {
                System.IO.Directory.CreateDirectory(dirFile);
            }
            QRCodeEncoder qrCodeEncoder = new QRCodeEncoder();
            qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;
            qrCodeEncoder.QRCodeScale = 8;
            qrCodeEncoder.QRCodeVersion = 0;
            qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M;
            System.Drawing.Image image = qrCodeEncoder.Encode(text);

            System.IO.FileStream fs = new System.IO.FileStream(newFilePath, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write);
            image.Save(fs, System.Drawing.Imaging.ImageFormat.Jpeg);

            fs.Close();
            image.Dispose();
            return string.Format("{0}/{1}/{2}", isAbsolute?catalogConfig.DestFile.AbsolutePath : catalogConfig.DestFile.RelativePath, catalog, newFileName);
        }
    }
}
